var fs = require("fs");
var path = require("path");
var mime = require("mime");

function serve(response, pathname) {
    var absPath = "./page" + pathname;
    console.log(absPath);
    fs.exists(absPath, function(exists) {
        if(exists) {
            fs.readFile(absPath, 'utf8', function(err,data) {
                if(err) {
                    console.log("can't read the file");
                    response.writeHead(404,{"Content-Type":"text/plain"});
                    response.write("404, can't read the file: " + absPath);
                    response.end();
                }
                else {
                    console.log("readFIle succeed");
                    response.writeHead(200,{"Content-Type" : mime.lookup(path.basename(pathname))});
                    response.write(data);
                    response.end();
                }
            });
        }
        else {
            console.log("can't find the file");
            response.writeHead(404,{"Content-Type":"text/plain"});
            response.write("404, can't find the file: " + absPath);
            response.end();
        }
    });
}

exports.serve = serve;